import TileMapMaterial from './TileMapMaterial';
import Utils from '../../../common/Utils';

export default class ImageTileMapMaterial extends TileMapMaterial {

    static type = 'image';

    constructor(tileMap) {
        super(tileMap);
    }

    static getUniqueKey(res) {
        return res.src;
    }

    async load(res) {
        if (this.image == null || this.image.src !== res.src) {
            this.image = await Utils.loadImage(res.src);
        }
        this.tileWidth = res.tileWidth || this.config.tileWidth;
        this.tileHeight = res.tileHeight || res.tileWidth || this.config.tileHeight;
        this.imageWidth = this.image.width;
        this.imageHeight = this.image.height;
        this.previewWidth = Math.floor(this.imageWidth / this.tileWidth); 
        this.previewHeight = Math.floor(this.imageHeight / this.tileHeight); 
    }

    draw(cell, tile) {
        let src = tile.src;
        let dst = cell.pos;
        this.canvasContext.drawImage(
            this.image,
            src[0] * this.tileWidth,
            src[1] * this.tileHeight,
            this.tileWidth,
            this.tileHeight,
            dst[0] * this.config.tileWidth,
            dst[1] * this.config.tileHeight,
            this.config.tileWidth,
            this.config.tileHeight
        );
    }
}
